package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.UUID;

/**
 * 单点登录应用实践
 */
public class SSODemo01 {
    static String token;
    //模仿访问服务端的资源
    static void doGetResource(){
        //1.检查token是否存在,(token是存储在客户端-Cookie,localStorage)
        if(token==null){
            System.out.println("please login");
            return;
        }
        //2.检查token是否已经失效
        Jedis jedis=new Jedis("192.168.126.130",6379);
        String user = jedis.get(token);
        jedis.close();
        if(user==null){
            System.out.println("login timeout or token invalid");
            return;
        }
        //3.返回你要访问的资源
        System.out.println("return user resource");
    }
    static void doLogin(String username,String password){
        if("jack".equals(username)&&"123456".equals(password)){
            System.out.println("login ok");
            String token= UUID.randomUUID().toString();
            Jedis jedis=new Jedis("192.168.126.130",6379);
            jedis.set(token,username);//存储用户信息
            jedis.expire(token,1);
            jedis.close();
            //将token存储到客户端
            SSODemo01.token=token;
            return;
        }
        System.out.println("username or password error");
    }
    public static void main(String[] args) throws InterruptedException {//这里的main方法代表客户端
        //1.访问资源
        doGetResource();
        //2.执行登录操作
        doLogin("jack","123456");
        //3.再次访问资源
        Thread.sleep(1000);
        doGetResource();
    }
}
